package com.wtwd.campus.receiver;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.dao.CommandRecordMapper;
import com.wtwd.campus.dao.DeviceInfoMapper;
import com.wtwd.campus.dao.SosCallMapper;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.h5_manager.entity.DeviceLog;
import com.wtwd.campus.h5_manager.service.DeviceLogService;
import com.wtwd.campus.utils.ReceiverUtils;
import com.wtwd.campus.vcom.common.Constant;
import com.wtwd.campus.vcom.dao.RequestRecordMapper;
import com.wtwd.campus.vcom.dao.VcomPhoneMapper;
import com.wtwd.campus.vcom.entity.VcomPhoneData;
import com.wtwd.campus.vcom.entity.VcomRequestRecord;
import com.wtwd.campus.vcom.service.impl.VcomDeviceInfoServiceImpl;
import com.wtwd.campus.vcom.utils.VcomPushUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mjy
 * @date 2021/07/20
 * @description
 */
@Service
@MsgType(value = Constants.ALL_SOS_PHONE)
public class SetAllSosReceiver implements IReceiverHandler {

    @Autowired
    private CommandRecordMapper commandRecordMapper;

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @Autowired
    private ReceiverUtils receiverUtils;

    @Autowired
    private SosCallMapper sosCallMapper;

    @Autowired
    private VcomDeviceInfoServiceImpl vcomDeviceInfoService;

    @Autowired
    private VcomPhoneMapper vcomPhoneMapper;

    @Autowired
    private RequestRecordMapper requestRecordMapper;

    @Autowired
    private VcomPushUtils vcomPushUtils;

    @Autowired
    private DeviceLogService deviceLogService;

    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqAllSosResult mqAllSosResult = (MqAllSosResult) mqMessage.getObject();
        String imei = mqAllSosResult.getImei();
        String commandNumber = mqAllSosResult.getCommandNumber();
        //处理指令回复的时间
        String deviceDate = mqAllSosResult.getDeviceDate();
        String deviceTime = mqAllSosResult.getDeviceTime();
        Long time = getTime(deviceDate, deviceTime);
        DeviceInfo deviceInfo = deviceInfoMapper.getDeviceInfoByImei(mqAllSosResult.getImei());
        if (deviceInfo != null) {
            //定位信息处理
            MqLocationData mqLocationData = mqAllSosResult.getMqLocationData();
            if (mqLocationData != null) {
                if (mqLocationData.getLatitude() != 0 && mqLocationData.getLongitude() != 0) {
                    //进行定位数据存储以及围栏告警记录的存储
                    deviceInfo = receiverUtils.dealLocation(mqAllSosResult.getMqLocationData(), time, deviceInfo, 1);
                }
            }
            if (deviceInfo.getDeviceType() == Constant.VCOM_DEVICE_TYPE && deviceInfo.getCustomerId() == 1) {
                //处理威科姆设备上报信息
                dealVcomDevice(deviceInfo, mqAllSosResult.getSosCallList(), commandNumber, time);
            } else {
                //处理平台设备上报信息
                dealPlatDevice(mqAllSosResult, deviceInfo, commandNumber, time);
            }
            //修改设备信息
            deviceInfo.setLastUpTime(time);
            deviceInfoMapper.modifyDeviceInfo(deviceInfo);
            //删除缓存中的指令
            String delKey = Constants.ALL_SOS_PHONE.concat("-").concat(commandNumber);
            receiverUtils.deleteCommandInRedis(imei, delKey);
            //存储设备接收日志
            DeviceLog deviceLog = new DeviceLog();
            deviceLog.setSendUser(Constants.DEVICE_USER);
            deviceLog.setImei(imei);
            deviceLog.setBigType(Constants.MESS_TYPE);
            deviceLog.setType(Constants.ALL_SOS_PHONE);
            JSONObject contant = new JSONObject();
            contant.put("设备号", imei);
            contant.put("日期", mqAllSosResult.getDeviceDate());
            contant.put("经度",mqAllSosResult.getMqLocationData().getLongitude());
            contant.put("纬度", mqAllSosResult.getMqLocationData().getLatitude());
            contant.put("速度",mqAllSosResult.getMqLocationData().getSpeed());
            contant.put("方位角", mqAllSosResult.getMqLocationData().getOrientation());
            contant.put("设备回复sos数据集合", mqAllSosResult.getSosCallList());
            contant.put("时间",mqAllSosResult.getDeviceTime());
            deviceLog.setCmd(contant.toJSONString());
            deviceLog.setSendTime(System.currentTimeMillis());
            deviceLog.setCommandNumber(commandNumber);
            deviceLog.setState(1);
            deviceLogService.addDeviceLog(deviceLog);
        } else {
            saveUnInStorage(imei);
            receiverUtils.cloaseChannel(imei);
        }
    }

    /**
     * 处理平台设备
     */
    public void dealPlatDevice(MqAllSosResult mqAllSosResult, DeviceInfo deviceInfo, String commandNumber, Long time) {
        String imei=deviceInfo.getImei();
        CommandRecord commandRecord = commandRecordMapper.getCommandRecordByCondition2(imei, commandNumber, Constants.ALL_SOS_PHONE);
        if (commandRecord != null) {
            List<DeviceSOSList> sosCallList = mqAllSosResult.getSosCallList();
            if (sosCallList != null && sosCallList.size() > 0) {
                ArrayList<Integer> delSequence = new ArrayList<>();
                ArrayList<DeviceSOSList> updateSosList = new ArrayList<>();
                for (DeviceSOSList deviceSOS : sosCallList) {//回复发送只记录了name,phone，sequence
                    if (StringUtils.isBlank(deviceSOS.getSosPhone())) {//如果手机号码为空，则删除
                        delSequence.add(deviceSOS.getSequence());
                    } else {//记录添加或者修改
                        deviceSOS.setDeviceId(deviceInfo.getDeviceId());
                        deviceSOS.setCommandNumber(commandNumber);
                        deviceSOS.setStatus(Constants.DEVICE_SOS_NORMAl);
                        updateSosList.add(deviceSOS);
                    }
                }
                if (delSequence != null && delSequence.size() > 0) {//执行删除
                    sosCallMapper.bathDelSosCallByDeviceIdAndSequence(deviceInfo.getDeviceId(), delSequence);
                }
                if (updateSosList != null && updateSosList.size() > 0) {
                    sosCallMapper.updateSosCallByDeviceIdAndSequence(updateSosList);
                }
            }
            //将指令状态改为完成
            commandRecordMapper.completeCommand(commandRecord.getId(), System.currentTimeMillis());
        }
    }


    /**
     * 处理Vcom的设备
     */
    public void dealVcomDevice(DeviceInfo deviceInfo, List<DeviceSOSList> sosList, String commandNumber, Long time) {
        String imei = deviceInfo.getImei();
        if (deviceInfo.getDeviceType() == Constant.VCOM_DEVICE_TYPE) {
            if (sosList != null) {
                //完善号码记录表
                VcomPhoneData phoneRecord = vcomPhoneMapper.getPhoneListByType(deviceInfo.getImei(), Constant.PHONE_SOS);
                if (phoneRecord == null) {
                    return;
                }
                int type = phoneRecord.getType();
                //解析并补全设备上报数据
                List<Map<String, Object>> saveList = new ArrayList<>();
                for (DeviceSOSList sos : sosList) {
                    if (sos.getSequence() == 1) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("name", sos.getSosName());
                        map.put("phone", sos.getSosPhone());
                        map.put("sequence", sos.getSequence());
                        saveList.add(map);
                    }
                }
                for (int i = 2; i <= 3; i++) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", "");
                    map.put("phone", "");
                    map.put("sequence", i);
                    saveList.add(map);
                }
                //修改内容、完成状态、修改时间
                phoneRecord.setPhoneData(JSONObject.toJSONString(saveList));
                phoneRecord.setStatus(Constant.PHONE_STATUS_NORMAL);
                phoneRecord.setUpdateTime(time);
                vcomPhoneMapper.modifyPhoneRecordStatus(phoneRecord);
                //完善请求表
                VcomRequestRecord requestRecord = requestRecordMapper.getRequestRecord(imei, commandNumber, type);
                if (requestRecord == null) {
                    return;
                }
                requestRecord.setCompleteTime(time);
                requestRecord.setStatus(Constant.STATUS_COMPLETE);
                requestRecordMapper.modifyRequestRecord(requestRecord);
                //选择一条指令进行下发
                VcomRequestRecord oldestSending = requestRecordMapper.getOldestSendingCommand(imei, type);
                if (oldestSending == null) {
                    VcomRequestRecord oldestNotSend = requestRecordMapper.getOldestNotSendCommand(imei, type);
                    if (oldestNotSend !=null && !requestRecord.getRequestId().equals(oldestNotSend.getRequestId())) {
                        //进行指令下发(将正在下发的指令置为正在执行状态)
                        requestRecordMapper.updateCommandSendStatus(oldestNotSend.getId(), Constant.STATUS_SEND);
                        JSONArray object = JSONObject.parseArray(oldestNotSend.getRequestContent());
                        vcomDeviceInfoService.useDealSos(object, oldestNotSend);
                    }
                }
                // 推送给Vcom
                vcomPushUtils.commandComplete(imei,commandNumber,type,Constant.PHONE_STATUS_NORMAL);
            }
        }
    }


}
